#ifndef __TCPSERVER_HPP__
#define __TCPSERVER_HPP__
#include "common.hpp"

/***************************************************acceptclient*********************************************************************/
class acceptclient
{
private:
    void *parent;           // 指向tcpserver

    std::string serverIP;
    uint16_t serverPort;
    std::string acceptIP;
    uint16_t acceptPort;

    uv_loop_t *loop;
    uv_tcp_t acceptHandle;

    uv_buf_t uvRbuf;
    uv_mutex_t rMutex;
    uint8_t *rbuff;
    int32_t rbuffIn;
    int32_t rbuffOut; 

    uv_timer_t sendTimer;
    int32_t repeatSendTime;
    uv_async_t sendAsync;
    uv_mutex_t sMutex;
    uint8_t *sbuff;
    int32_t sbuffIn;
    int32_t sbuffOut;
    uv_write_t write_reqs;

    bool isConnect; 

public:
    acceptclient(uv_loop_t *ploop, uv_stream_t* server, std::string server_ip, uint16_t server_port);
    ~acceptclient();

    std::string acceptGetIP();
    uint16_t acceptGetPort();
    int32_t acceptRecvData(uint8_t *buff, int32_t buff_len);
    int32_t acceptSendData(uint8_t *sdata, int32_t sdata_len);
    int32_t acceptGetRemainSpace();

protected:
    static void sAcceptAllocBufferForRecv(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
    static void sAcceptAfterRecv(uv_stream_t* client, ssize_t nread, const uv_buf_t* buf);
    static void sAcceptAfterClose(uv_handle_t* handle);

    static void sAcceptSendTimer(uv_timer_t* handle);
    static void sAcceptSendAsync(uv_async_t *handle);
    static void sAcceptAfterSend(uv_write_t *req, int status);

private:
    void acceptStartSend(void);
    void acceptStopSend(void);
};





/*****************************************************tcpserver*********************************************************************/
class tcpserver
{
private:
    
    std::string serverIP;
    uint16_t serverPort;
    struct sockaddr_in addr;

    void *parent;                           // 指向上一层
    uv_loop_t *loop;
    uv_tcp_t serverHandle;   

    uv_mutex_t acceptMutex;
    std::vector<class acceptclient *>acceptclientVec;

public:
    tcpserver(uv_loop_t *ploop, std::string server_ip, uint16_t server_port);
    ~tcpserver();

    int32_t tsDeleteAcceptClient(uv_stream_t *client, std::string accept_ip, uint16_t accept_port);

    int32_t tsGetAcceptClientRecvData(std::string accept_ip, uint16_t accept_port, uint8_t *buff, int32_t buff_len);
    int32_t tsSetAcceptClientSendData(std::string accept_ip, uint16_t accept_port, uint8_t *sdata, int32_t sdata_len);
    int32_t tsGetAcceptClientRemainSpace(std::string accept_ip, uint16_t accept_port);

protected:
    static void AcceptConnection(uv_stream_t* server, int status);
};




#endif
